package ni;


import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import main.ChatNI;
import cs.remoteapp.Message;

/**
 * Executes sending message
 * Package  ni
 * Project ChatSystemG5 - INSA 4INFOA1 - 2013/2014
 * @author thomas Vuillemin Martin ConantO
 */
public class UdpSender extends Udp {

	/**
	 * Constructor who open a socket
	 * @param port the port on which the socket must be open
	 * @param ni the object ChatNI
	 */
	public UdpSender(int port, ChatNI ni)
	{
		super(ni);
		this.port = port;
		openUdpSocket(this.port);
	}
	
	/**
	 * Constructor who use a previously open socket passed in parameter
	 * @param socket the previously open socket
	 * @param ni the object ChatNI
	 */
	public UdpSender(DatagramSocket socket, ChatNI ni)
	{	
		super(ni);
		this.socket = socket;
		this.port = socket.getLocalPort();
	}
	
	/**
	 * Send a message via udp on the socket.
	 * @param message the Message object to be send
	 * @param address the InetAddress of the receiver
	 */
	public void sendData(Message message, InetAddress address)
	{
		
		try {
			//FileOutputStream fichier = new FileOutputStream("helloSerialized.txt");
			ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(message);
			DatagramPacket packet = new DatagramPacket(bos.toByteArray(), bos.size());
	        packet.setAddress(address);
	        packet.setPort(ChatNI.PORT);
			this.socket.send(packet);
			System.out.println("udpSender sent a message through port " + this.port + " to " + address.toString() + " IP address");
			//oos.flush();
			//oos.close();
		}
		catch (java.io.IOException e) {
			System.out.println("udpSender could not send a message through port " + this.port + " to " + address.toString() + " IP address");
			e.printStackTrace();
		}
		
		
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}

}